package com.za.wbw.web.shop.action;

import java.util.HashMap;
import java.util.Map;

import com.za.wbw.model.shop.ShopInfo;
import com.za.wbw.model.shop.UserInfo;
import com.za.wbw.service.shop.LoginService;
import com.za.wbw.service.shop.ShopService;
import com.za.wbw.util.BaseAction;
import com.za.wbw.util.StringUtil;

public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private LoginService loginService;
	private ShopService shopService;
	// 登 录
	public String login() throws Exception{
		int count = this.getLoginService().queryShopCount();
		request.setAttribute("shop_count", count);
		return SUCCESS;
	}
	// 登录
	public String submit() throws Exception {
		// 用户名为空
		String account = request.getParameter("account");
		if(StringUtil.isNullOrEmpty(account))
		{
			request.setAttribute("message", "请您输入用户名？");
			return ERROR;
		}
		// 密码为空
		String password = request.getParameter("password");
		if(StringUtil.isNullOrEmpty(password))
		{
			request.setAttribute("message", "请您输入密码？");
			return ERROR;
		}
		// 验证码
		String verify = request.getParameter("verify");
		if(StringUtil.isNullOrEmpty(verify))
		{
			request.setAttribute("message", "请您输入验证码？");
			return ERROR;
		}
		if(!verify.equals(request.getSession().getAttribute("verify"))){
			request.setAttribute("message", "您输入的验证码有误,请重新输入？");
			return ERROR;
		}
		request.getSession().removeAttribute("verify");
		// 查询用户
		UserInfo user = this.getLoginService().queryUserByAccount(account);
		// 用户不存在
		if(user == null){
			request.setAttribute("message", "您输入的密码和账户名不匹配，请重新输入。或者您忘记了密码？");
			return ERROR;
		}
		// 密码不匹配
		if(!password.equals(user.getUserPassword())){
			request.setAttribute("message", "您输入的密码和账户名不匹配，请重新输入。或者您忘记了密码？");
			return ERROR;
		}
		ShopInfo shop = getShopService().queryShopInfo(user.getShopId());
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("user_id", user.getUserId());
		map.put("user_name", user.getUserName());
		map.put("shop_id", user.getShopId());
		map.put("shop_name", shop.getShopName());
		map.put("shop_address", shop.getAreaName()+shop.getStreetDoor());
		request.getSession().setAttribute("_info", map);
		// 返回
		return SUCCESS;
	}
	// ----------------------------------
	public LoginService getLoginService() {
		return loginService;
	}
	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	public ShopService getShopService() {
		return shopService;
	}
	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}
}
